<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./vue.js"></script>
</head>
<body>
    <div id="app">
        <h2>{{message}}</h2>
        <com-a></com-a>
    </div>
    <template id="coma">
        <div>
            <h2>我是coma组件</h2>
            <button @click="sendevent">点击我发送事件</button>
        </div>

    </template>
    <script>
        class MyEvent {
            constructor() {
                this.handler = {};
            }
            // 添加事件
            addEvent(eventName, fn) {
                // 通过 handle 来保存下来，等到需要执行的时候在执行
                // {自定义事件名(click):[fn1,fn2,fn3...]}
                if (typeof this.handler[eventName] == "undefined") {
                    // 把对象初始化成一个数组
                    this.handler[eventName] = [];
                    // {myevent:[fn,fn1,fn2]}
                }
                this.handler[eventName].push(fn)
            }
            trigger(eventName,playload) {
                this.handler[eventName].forEach(fn => {
                    fn(playload);
                })
            }
        }




        // 总线模式（观察者模式）;

        // let $bus = new Vue();
        // Vue.prototype.$bus = new Vue();
        Vue.prototype.$bus = new MyEvent();

        let ComA = {
            template:"#coma",
            data:function(){
                return {
                    message:"子组件数据"
                }
            },
            methods:{
                sendevent(){
                    console.log("sendevent")
                    // trigger  click ...
                    this.$bus.trigger("myevent",this.message);
                }
            }
        }

        new Vue({
            el:"#app",
            components:{
                ComA 
            },
            data:{
                message:"数据"
            },
            mounted:function(){
                // addevetn
                // 监听自定义事件
                this.$bus.addEvent("myevent",res=>{
                    console.log("on");
                    this.message = res;
                })
            }
        })


    </script>
</body>
</html>